# -*- coding: utf-8 -*-..,
##############################################################################
#
#    @author: PhongND
#    Copyright (C) 2014 Crea8s (http://www.crea8s.com) All Rights Reserved.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from pickle import TRUE


# -*- coding: UTF-8 -*-
'''
    magento

    :copyright: (c) 2014-2015 by PhongND
    :license: AGPLv3, see LICENSE for more details
'''
import magento
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp


class Delivery(osv.Model):
    """Delivery
    """
    _name = 'stock.picking.magento'
    _table = "stock_picking"
    _inherit = 'stock.picking'
    _description = "Import deliveries from Magento system"

    _columns = dict(
        crea8s_magento_id=fields.integer('Magento ID', readonly=True),
        crea8s_magento_instance=fields.many2one(
            'crea8s.magento.instance', 'Magento Instance', readonly=True,
        ),
        crea8s_magento_store=fields.many2one(
            'crea8s.magento.store', 'Store', readonly=True,
        ),
    )
    
    _sql_constraints = [(
        'magento_id_instance_unique', 'unique(crea8s_magento_id, crea8s_magento_instance)',
        'A delivery must be unique in an instance' # PhongND
    )]
    
    
    def crea8s_print_text(
        self, strText, context=None
    ):
        print 'def crea8s_print_text: strText: ' + strText
        print '+ magento_instance: ' + str(context.get('magento_instance', 'empty'))
        print '+ magento_website: ' + str(context.get('magento_website', 'empty'))
    
    def crea8s_find_or_create_using_magento_data(
        self, cursor, user, data_importing, context
    ):
        """
        Find or Create delivery using magento data

        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento
        :param context: Application context
        :returns: Browse record of delivery Delivery found/created
        """
        delivery = self.crea8s_find_using_magento_data(
            cursor, user, data_importing, context
        )
        
        if not delivery:
#             return False
            delivery = self.crea8s_create_using_magento_data(
                cursor, user, data_importing, context
            )
        else:
            delivery = self.crea8s_create_using_magento_data(
                cursor, user, data_importing, context, updateID = delivery.id
            )

        return delivery

    def crea8s_find_using_magento_data(
        self, cursor, user, data_importing, context
    ):
        """
        Create delivery using magento data
         
        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento
        :param context: Application context
        :returns: Browse record of delivery Delivery found
        """
        # each delivery has to be unique in an instance of magento...
        delivery_ids = self.search(cursor, user, [
            ('crea8s_magento_id', '=', int(data_importing['shipment_id'])),
            ('crea8s_magento_instance', '=', int(context.get('magento_instance'))),
        ], context=context)

        return delivery_ids and self.browse(
            cursor, user, delivery_ids[0], context
        ) or None

    def crea8s_create_using_magento_data(self, cursor, user, data_importing, context, updateID=None):
        """
        Create a delivery Delivery from magento data
 
        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento
        :param context: Application context
        :param updateID: delivery.id
        :returns: Browse record of delivery Delivery created
        """
        ormCurrency = self.pool.get('res.currency')
        ormInstance = self.pool.get('crea8s.magento.instance')
        ormStore = self.pool.get('crea8s.magento.store')
        ormView = self.pool.get('crea8s.magento.view')
        ormPartner = self.pool.get('res.partner')
        ormPicking = self.pool.get('stock.picking')
        ormPickinglines = self.pool.get('stock.picking.line')
        ormSaleOrder = self.pool.get('sale.order')
        ormSOline = self.pool.get('account.invoice.line')
 

#         objView = ormView.browse(
#             cursor, user, context['magento_view'], context
#         )
#         if not objView.store.shop:
#             raise osv.except_osv(
#                 _('Not Found!'),
#                 _(
#                     'Magento Store \'%s\' should have a shop configured.'
#                     % objView.store.name
#                 )
#             )
#         if not objView.store.shop.pricelist_id:
#             raise osv.except_osv(
#                 _('Not Found!'),
#                 _(
#                     'Shop on store \'%s\' does not have a pricelist!'
#                     % objView.store.name
#                 )
#             )
        
        #find instance
        objInstance = ormInstance.browse(
            cursor, user, context['magento_instance'], context
        )
        
        #find invoice
        arrSO_ids = ormSaleOrder.search(
            cursor, user, [('crea8s_magento_instance', '=', objInstance.id),
                           ('crea8s_magento_id', '=', data_importing['order_id']),
                           ], context=context
        )
        intSO_id = (len(arrSO_ids)>0) and arrSO_ids[0] or None
        objSO = ormSaleOrder.browse(
            cursor, user, 
            intSO_id, context)
        
        # finding stock.location
        #    stock_picking.stock_journal_id === stock_location.chained_journal_id
        intLocation = None
        ormStore = self.pool.get('crea8s.magento.store')
        objStore = ormStore.browse(cursor, user, context.get('magento_store'), context=context)
        outLocation = objStore and objStore.shop.warehouse_id.lot_output_id or None
        intLocation = outLocation.chained_journal_id and outLocation.chained_journal_id.id or None
        
        
        
#         currencyid = None
#         currencyids = []
#         currencyids = ormCurrency.search(
#             cursor, user, [('name', 'ilike', data_importing['deliveryAAA_currency_code'])], context=context
#         ) # == ormCurrency.search_using_magento_code(
#         if len(currencyids) > 0:
#             currencyid = currencyids[0]
        
        
#         'shipping_address_id': '2''
#         'billing_address_id': '1'
        
#         print '+delivery.py > crea8s_create...: ormPartner.crea8s_find_or_create_using_magento_id.....'
#         partner = ormPartner.crea8s_find_or_create_using_magento_id(
#             cursor, user, data_importing['customer_id'], context
#         )
 
#         partner_invoice_address = \
#             ormPartner.crea8s_find_or_create_address_as_partner_using_magento_data(
#                 cursor, user, data_importing['billing_address'], partner, context
#             )
# 
#         partner_shipping_address = \
#             ormPartner.crea8s_find_or_create_address_as_partner_using_magento_data(
#                 cursor, user, data_importing['shipping_address'], partner, context
#             )
 
        delivery_data = {
                         
            'name': str(objInstance.order_prefix) + 'OUT/' + data_importing['increment_id'], # increment_id
            'origin': objSO and objSO.name or None,
            'date': data_importing['created_at'].split()[0],
            'type': 'out', # types: out | internal | in 
            'state': 'auto',
            'move_type': objSO and objSO.picking_policy or None,
            'sale_id': objSO and objSO.id or None, #
            'partner_id': objSO and objSO.partner_id.id or None,  # objSO.partner_shipping_id.id,
            'note': objSO and objSO.note or None, # ??, description
            'invoice_state': (objSO.order_policy=='picking' and '2binvoiced') or 'none',  #?? invoice_state 
            'company_id': objSO and objSO.company_id.id or None,
            'stock_journal_id': intLocation,
            
            #magento identity.
            'crea8s_magento_id': int(data_importing['shipment_id']),
            'crea8s_magento_instance': objInstance.id,
#             'move_lines': [],
            'move_lines': self.crea8s_get_item_line_data_using_magento_data(
                cursor, user, data_importing, context
            )



#             'name': str(objInstance.order_prefix) + data_importing['increment_id'], # increment_id  
#             
#             'date': data_importing['created_at'].split()[0],
#             'partner_id': partner.id,
# #             'pricelist_id': objView.store.shop.pricelist_id.id,
#             'currency_id': None, #currencyid # currency.id,
#             'partner_invoice_id': 6, #partner_invoice_address.id,
#             'partner_shipping_id': 6, #partner_shipping_address.id,
#             
        }
 
#         if float(data_importing.get('shipping_amount')):
#             print 'delivery.py: shipping_amount.....'
#             delivery_data['deliveryAAA_line'].append(
#                 self.crea8s_get_shipping_line_data_using_magento_data(
#                     cursor, user, data_importing, context
#                 )
#             )
# #  
#         if float(data_importing.get('discount_amount')):
#             print 'delivery.py: discount_amount.....'
#             delivery_data['deliveryAAA_line'].append(
#                 self.crea8s_get_discount_line_data_using_magento_data(
#                     cursor, user, data_importing, context
#                 )
#             )
 
 
        
        delivery_id = None
        if updateID:
            # remove SO lines
            arrSOline_ids = ormSOline.search(cursor, user, [('id', '=', updateID)], context=None) # not search: shipment_id
#             ormSOline.unlink(cursor, user, arrSOline_ids, context=None)
             
            # update SO
            delivery_id = self.write(cursor, user, [updateID], delivery_data, context=context)
            delivery_id = updateID
        else:
            delivery_id = self.create(
                cursor, user, delivery_data, context=context
            ) 
            # ok, 
#             delivery_id = ormSaleOrder._create_pickings_and_procurements(cursor, user, objSO, objSO.order_line, None, context=context)

        
#         # Process delivery now
#         self.process_sale_using_magento_state(
#             cursor, user, delivery, data_importing['state'], context
#         )
#         
        delivery = self.browse(cursor, user, delivery_id, context)
        return delivery
    
    
    """
        override _prepare_order_picking
        
        :author: PhongND
        :param ...
        """
    def _prepare_order_picking(self, cursor, user, order, context=None):
        
        arrRe = super(Delivery, self)._prepare_order_picking(cursor, user, order, context=context)
        arrRe.update({
                      'crea8s_magento_id' : context.get('shipment_id'),
                      'crea8s_magento_instance' :  order.crea8s_magento_instance,
                      
                      })
        print 'delivery.py: _prepare_order_picking.....'
        return arrRe
        
    #?? discount...
    def crea8s_get_discount_line_data_using_magento_data(self, cursor, user, data_importing, context):
        """
        Create a discount line for the given delivery using magento data

        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento 
        :param context: Application context
        """
    
        ormWebsite = self.pool.get('crea8s.magento.website')
        return (0, 0, {
            'name': 'Magento Discount', # ....data_importing['discount_description'] or
            'price_unit': float(data_importing.get('discount_amount', 0.00)),
            'product_uom':
                ormWebsite.get_default_uom(
                    cursor, user, context
            ).id,
            'magento_notes': data_importing.get('discount_description'),
        }) # (0, 0, {})
    
    
    #?? shipping
    def crea8s_get_shipping_line_data_using_magento_data(self, cursor, user, data_importing, context):

        print 'delivery.py: crea8s_get_shipping_line_data_using_magento_data'
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormProduct = self.pool.get('product.product')
        
#         taxes = self.crea8s_get_magento_shipping_tax(
#             cursor, user, data_importing, context
#         )
        
#         line_data = []
        values = {
            'name': 'Magento Shipping',
            'price_unit': float(data_importing.get('shipping_amount', 0.00)), #nono: shipping_incl_tax
            'product_uom': ormWebsite.get_default_uom(
                    cursor, user, context
            ).id,  # context: magento_website ???
#             'product_uom_qty': float(item['qty_deliveryAAAed']),
            'magento_notes': ' - '.join(['01', '02'
#                 data_importing['shipping_method'],
#                 data_importing['shipping_description']
            ]),
            'type': 'make_to_deliveryAAA',
#             'tax_id': [(6, 0, taxes)], #???
            
        }

        line_data = (0, 0, values) # ??, 0, 0, values   # okok
        
        print '+ line_data: ' + str(line_data)
        return line_data
        
        
    
    def crea8s_get_item_line_data_using_magento_data(self, cursor, user, data_importing, context):
        """
        Create a delivery Delivery from magento data
 
        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento
        :param context: Application context
        :returns: Browse record of delivery Delivery created
        """
        
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormStore = self.pool.get('crea8s.magento.store')
        ormProduct = self.pool.get('product.product')
        ormMRP_Bom = self.pool.get('mrp.bom') #???

        objStore = ormStore.browse(cursor, user, context.get('magento_store'), context=context) 
        line_data = []
        for item in data_importing['items']:
            if not item.get('parent_item_id'): #??

#                 taxes = self.crea8s_get_magento_taxes(cursor, user, item, context)
                # If its a top level product, create it
                values = {
                    'name': item['name'],
        #             'picking_id': picking_id,
                    'product_id':
                                ormProduct.crea8s_find_or_create_using_magento_id(
                                    cursor, user, item['product_id'],
                                    context=context, 
                                    ).id,
                                  
                    'date': data_importing['created_at'],
                    'date_expected': data_importing['created_at'],
#                     'date_expected': (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
                    'product_qty': float(item['qty']),
                    'product_uom': ormWebsite.get_default_uom(
                                    cursor, user, context,
                                    ).id,  # context: magento_website ???
        #             'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty,
        #             'product_uos': (line.product_uos and line.product_uos.id)\
        #                     or line.product_uom.id,
        #             'product_packaging': line.product_packaging.id,
        #             'partner_id': line.address_allotment_id.id or order.partner_shipping_id.id,
                    'location_id': objStore and objStore.shop.warehouse_id.lot_output_id.id or None,
                    'location_dest_id': objStore and objStore.shop.warehouse_id.lot_input_id.id or None,
        #             'sale_line_id': line.id,
#                     'move_history_ids': [],
#                     'move_history_ids2': [],
                    'tracking_id': False,
                    'state': 'draft',
                    #'state': 'waiting',
        #             'company_id': order.company_id.id,
        #             'price_unit': line.product_id.standard_price or 0.0,
            
            
                }
                line_data.append((0, 0, values))

        return line_data
    
    
    #????????
    def crea8s_get_magento_taxes(self, cursor, user, item_data, context):
        """Match the tax in openerp with the tax rate from magento
        Use this tax on delivery line

        :param cursor: Database cursor
        :param user: ID of current user
        :param item_data: Item Data from magento
        :param context: Application context
        """
        ormTax = self.pool.get('account.tax')

        # Magento does not return the name of tax
        # First try matching with the percent
        tax_ids = ormTax.search(cursor, user, [
            ('amount', '=', float(item_data['tax_percent']) / 100),
#             ('crea8s_used_on_magento', '=', True) ,
        ], context=context)

        # FIXME This will fail in the case of bundle products as tax comes
        # comes with the children and not with parent

        return tax_ids
    
    #????????
    def crea8s_get_magento_shipping_tax(self, cursor, user, data_importing, context):
        """Match the tax in openerp which has been selected to be applied on
        magento shipping.

        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Delivery Data from magento
        :param context: Application context
        """
        ormTax = self.pool.get('account.tax')

        # Magento does not return the name of tax or rate
        # We can match only using the field set on tax in openerp itself
        tax_ids = ormTax.search(cursor, user, [
#             ('crea8s_apply_on_magento_shipping', '=', True),
#             ('crea8s_used_on_magento', '=', True),
        ], context=context)

        return tax_ids
    
    
    
    
    
    
    
    
    
    
    
    
